package com.cjy.thread.lock;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/*
    匿名内部类
    前提：必须是类或者接口

    格式：
        new 类名/接口名（）{
            重写抽象方法
        }
 */
public class TestLock {
        private static Lock lock = new ReentrantLock();
        private static Condition newScore = lock.newCondition();
        private static int score=0;

    public static void main(String[] args) {
        ExecutorService executor = Executors.newFixedThreadPool(2);
        new Thread(){
            @Override
            public void run() {
                try {
                    while (true){
                        extraPoints((int)(Math.random()*10)+1);
                        Thread.sleep(1000);
                    }
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }.start();
        new Thread(){
            @Override
            public void run() {
                while (true){
                    minus((int)(Math.random()*10)+1);
                }
            }
        }.start();
        System.out.println("加分\t\t扣分\t\t总分");
    }
    public static int getScore(){
        return score;
    }
    public static void extraPoints(int number){
        lock.lock();
        try {
            score += number;
            System.out.println(number+"\t\t\t\t"+getScore());
            newScore.signal();
        }finally {
            lock.unlock();
        }
    }
    public static void minus(int number){
        lock.lock();
        try {
            while (score<number){
                System.out.println("\t\t不够减"+number);
                newScore.await();
            }
            score -= number;
            System.out.println("\t\t"+number+"\t\t"+getScore());
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }finally {
            lock.unlock();
        }
    }
}
